import json
import time
from json import JSONDecodeError

from PySide6.QtCore import QThread

from ch9329 import CH9329


#
# class Player:
#     def __init__(self, ch9329: CH9329):
#         self.ch9329 = ch9329
#         self.prev_time = 0
#         self.play_flag = False
#
#     def in_play(self):
#         return self.play_flag
#
#     def play(self, filepath):
#         self.play_flag = True
#         with open(filepath, 'r') as file:
#             lines = file.readlines()
#         for line in lines:
#             if not self.play_flag:
#                 return
#             try:
#                 func = json.loads(line)
#                 delay = func["delay"] - self.prev_time
#                 time.sleep(delay / 1000)
#                 self.prev_time = func["delay"]
#
#                 if self.ch9329 is not None:
#                     cmd = "self.ch9329." + func["type"] + "." + func["cmd"]
#                     try:
#                         eval(cmd)
#                     except (AttributeError, SyntaxError) as ex:
#                         print(ex)
#                         pass
#             except JSONDecodeError as ex:
#                 print("JSON 解析出错", ex.doc, ex.msg)
#         self.prev_time = 0
#         self.play_flag = False
#
#     def stop(self):
#         self.prev_time = 0
#         self.play_flag = False


class PlayThread(QThread):
    def __init__(self, ch9329: CH9329, filepath: str):
        super().__init__()
        self.ch9329 = ch9329
        self.filepath = filepath
        self.play_flag = False
        self.prev_time = 0

    def run(self):
        self.play_flag = True
        with open(self.filepath, 'r') as file:
            lines = file.readlines()
        for line in lines:
            if not self.play_flag:
                break
            try:
                func = json.loads(line)
                delay = func["delay"] - self.prev_time
                time.sleep(delay / 1000)
                self.prev_time = func["delay"]

                if self.ch9329 is not None:
                    cmd = "self.ch9329." + func["type"] + "." + func["cmd"]
                    print(cmd)
                    try:
                        eval(cmd)
                    except (AttributeError, SyntaxError) as ex:
                        print(ex)
                        pass
            except JSONDecodeError as ex:
                print("JSON 解析出错", ex.doc, ex.msg)

    def stop(self):
        self.play_flag = False
